<?php
/**
 * Created by PhpStorm.
 * User: Echa
 * Date: 2016/10/23
 * Time: 14:01
 */
namespace SDXApi\Model;
use Think\Model;

class ThewarehouseacceptconfigModel extends Model
{
    protected $tableName = 'the_warehouse_accept_config';

    public function batch_warehouse_request_goods($wid=0) {
        ini_set('max_execution_time', '0');
        set_time_limit(0);
        if($wid){
           $twaclist=$this->where(array('wid'=>$wid))->select();   
        }else{
           $twaclist=$this->select();
        }
        if($twaclist){
            $the_warehouse_request_record_mod=M('the_warehouse_request_record');
            $the_warehouse_request_record_detail_mod=M('the_warehouse_request_record_detail');
            //$the_warehouse_requirements_mod=M('the_warehouse_requirements');
            $Goodsstorage_mod=D('Goodsstorage');
            $where='';
            $performxx_sn=gmtime();
            
            foreach ($twaclist as $k=>$v){
                $batch_sn=$this->get_batch_sn('JL');
                $sql='SELECT * FROM( SELECT g.goods_id,g.goods_sn,g.goods_name,IFNULL(t.goods_number_sum,0) as goods_number_sum,c.storage_requirements_for,c.id,g.sources FROM '.C('DB_PREFIX').'goods as g'.
                        ' LEFT JOIN('.
                        'SELECT SUM(a.goods_number) as goods_number_sum,a.goods_id,a.goods_sn FROM'.
                        '('.
                               'SELECT og.goods_id,og.goods_sn,og.goods_name,og.goods_number FROM '.C('DB_PREFIX').'order_info as oi'. 
                               ' LEFT JOIN '.C('DB_PREFIX').'order_goods as og ON oi.order_id=og.order_id'. 
                               " WHERE (oi.pay_status IN (2,3)) and og.is_presell=1 and og.buckle_inventory=0 AND oi.shipping_status in(0,1,3) AND  (oi.order_status NOT IN (2,3,4))  AND oi.pay_status!=4 AND (oi.best_time < UNIX_TIMESTAMP(date_format(now(),'%Y-%m-%d 23:59:59'))) and oi.wid=".$v['source_wid'].
                             ')as a'. 
                        ' GROUP BY a.goods_id'.
                        ') as t ON g.goods_id=t.goods_id'.
                        ' LEFT JOIN('.
                        'SELECT twr.id,twr.wid,gs.goods_id,gs.goods_sn,gs.goods_name,twr.storage_requirements_for FROM '.C('DB_PREFIX').'the_warehouse_requirements as twr'.
                        ' LEFT JOIN '.C('DB_PREFIX').'goods as gs ON twr.goods_id=gs.goods_id'. 
                        ' LEFT JOIN '.C('DB_PREFIX').'the_warehouse_accept_config AS twac ON twac.source_wid=twr.wid'.
                        ' WHERE twr.wid='.$v['source_wid'].
                        ') as c ON g.goods_id=c.goods_id'.
                        ' WHERE (t.goods_number_sum IS NOT NULL OR c.id IS NOT NULL)'.$where.' ORDER BY c.storage_requirements_for DESC) as gg GROUP BY goods_id';
                $goods=$this->query($sql);
                if($goods){
                    foreach ($goods as $key=>$val){
                        /*if($v['wid']==5 && $val['sources']=='891'){   //东圃区域仓-5  东圃-物料仓-7
                            continue;
                            //$where=" and g.sources<>'891'";
                        }
                        if($v['wid']==8 && $val['sources']!='891'){  //花城汇仓
                            continue;
                            //$where=" and g.sources='891'";
                        }*/
                        /*
                         * 当调仓需求数 ＞ 0，则该商品以该值向区域仓发送调仓需求
                                                                    当调仓需求数 ≤ 0，则该商品不向区域仓发送调仓需求
                                                                      调仓需求数 = 需求设定值 - 实际库存 + 订单内预售商品数
                         * */
                        $goodsstorage=$Goodsstorage_mod->get_warehous_goods($v['source_wid'],$val['goods_id']);
                        if($goodsstorage){
                            $practical_num=$goodsstorage['practical_num'];
                        }else{
                            $practical_num=0;
                        }
                        $goods_number_sum=$this->get_order_goods_id_list($val['goods_id'],$v['source_wid']);
                        if($goods_number_sum){
                            $val['goods_number_sum']=$val['goods_number_sum']-$goods_number_sum;
                        }
                        $the_warehouse_requirements_num=$val['storage_requirements_for']-$practical_num+$val['goods_number_sum'];
                        if($the_warehouse_requirements_num>0){
                                 $twrr_id=$the_warehouse_request_record_mod->where(array('batch_sn'=>$batch_sn))->getField('id');
                                 if($twrr_id){
                                     $twrrddata=array(
                                         'twrr_id'=>$twrr_id,
                                         'goods_id'=>$val['goods_id'],
                                         'goods_sn'=>$val['goods_sn'],
                                         'request_num'=>$the_warehouse_requirements_num
                                     );
                                     $the_warehouse_request_record_detail_mod->add($twrrddata);
                                     //调仓请求的“存仓需求量”在生成记录后清零
                                     //$the_warehouse_requirements_mod->where(array('id'=>$val['id'],'wid'=>$v['source_wid']))->save(array('storage_requirements_for'=>0));
                                 }else{
                                     $twrrdata=array(
                                         'batch_sn'=>$batch_sn,
                                         'wid'=>$v['wid'],
                                         'source_wid'=>$v['source_wid'],
                                         'add_time'=>gmtime(),
                                         'twr_id'=>1,
                                         'performxx_sn'=>$performxx_sn,
                                     );
                                     $twrr_id=$the_warehouse_request_record_mod->add($twrrdata);                              
                                     $twrrddata=array(
                                         'twrr_id'=>$twrr_id,
                                         'goods_id'=>$val['goods_id'],
                                         'goods_sn'=>$val['goods_sn'],
                                         'request_num'=>$the_warehouse_requirements_num
                                     );
                                     $the_warehouse_request_record_detail_mod->add($twrrddata);
                                     //调仓请求的“存仓需求量”在生成记录后清零
                                     //$the_warehouse_requirements_mod->where(array('id'=>$val['id'],'wid'=>$v['source_wid']))->save(array('storage_requirements_for'=>0));
                                 }
                        }
                    }
                }
            }
            return true;
        }else{
            return false;
        }
    }
    
/*
    * 根据商品ID，查询订单包含该商品数据
    * */
   private function get_order_goods_id_list($goods_id=0,$wid=0){
       $sql="SELECT og.goods_id,og.goods_sn,og.goods_name,og.goods_number,og.order_id FROM ".C('DB_PREFIX')."order_info as oi ".
            "LEFT JOIN ".C('DB_PREFIX')."order_goods as og ON oi.order_id=og.order_id ".
            "WHERE (oi.pay_status IN (2,3)) and og.is_presell=1 and og.buckle_inventory=0 AND oi.shipping_status in(0,1,3) AND  (oi.order_status NOT IN (2,3,4))  AND oi.pay_status!=4 AND (oi.best_time < UNIX_TIMESTAMP(date_format(now(),'%Y-%m-%d 23:59:59'))) and oi.wid=".$wid." and og.goods_id=".$goods_id;
       $order_goods=$this->query($sql);
       if($order_goods){
           $goods_number_sum=0;
           $refund_detail_mod=M('refund_detail');
           foreach ($order_goods as $k=>$v){
                     /*
                      * //检查退货退款时是否已经的处理，若有，该操作则进行对扣比较操作
                      * */
                     $rdlist=$refund_detail_mod->field('goods_id,SUM(refund_number) as refund_number')
                                                         ->where(array('order_id'=>$v['order_id'],'goods_id'=>$v['goods_id']))
                                                         ->find();
                     if($rdlist['refund_number']>0){
                         $goods_number_sum+=ceil($rdlist['refund_number']);//实际购买数量=购买数量-退款数量
                     }
           }
           return $goods_number_sum;
       }else{
           return false;
       }
   }  
    
    /*
     * 生成批次号
     * */
    private function get_batch_sn($prefix){
        /* 选择一个随机的方案 */
        mt_srand((double) microtime() * 1000000);
         
        return $prefix.date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }
}